package com.bst.web.base;

import com.bst.common.annotation.Log;
import com.bst.common.base.api.BaseDWService;
import com.bst.common.constant.JobConstant;
import com.bst.common.core.controller.BaseController;
import com.bst.common.core.domain.AjaxResult;
import com.bst.common.core.page.TableDataInfo;
import com.bst.common.enums.BusinessType;
import com.bst.common.exception.base.BaseException;
import com.bst.common.utils.DateUtil;
import com.bst.common.utils.DateUtils;
import com.bst.common.vo.DimDataVO;
import com.bst.md.domain.MdMedTb;
import com.bst.md.domain.MdMedTbFld;
import com.bst.system.service.ICommonTableDDLService;
import com.bst.md.service.IMdMedDimService;
import com.bst.md.service.IMdMedTbFldService;
import com.bst.md.service.IMdMedTbService;
import com.bst.system.vo.AlterTableParamVO;
import com.bst.system.vo.MdMedDimVO;
import com.bst.system.vo.MdMedTbFldVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.util.*;

@Controller
@RequestMapping("/md/med/dim")
@Api(tags="维度管理")
public class MdDimTbController extends BaseController {
    private String prefix = "system/md/med/dimTb";

    @Autowired
    IMdMedTbFldService mdMedTbFldService;
    @Autowired
    IMdMedDimService mdMedDimService;
    @Autowired
    ICommonTableDDLService commonTableDDLService;
    @Autowired
    IMdMedTbService mdMedTbService;
    @Autowired
    BaseDWService baseDWService;

    @GetMapping("")
    public String list()
    {
        return prefix + "/dimTb";
    }

    @GetMapping("/dimEditTb")
    public String dimEditTb()
    {
        return prefix + "/dimEditTb";
    }

    @GetMapping("/day")
    public String day(ModelMap mmap)
    {
        mmap.put("month",new SimpleDateFormat("yyyy-MM").format(new Date()));
        return prefix + "/day";
    }

    @GetMapping("/sfxm")
    public String sfxm(ModelMap mmap)
    {
        return "system/md/med/sfxm/sfxm_group";
    }

    @PostMapping("/queryDayByMonth")
    @ResponseBody
    public TableDataInfo queryDayByMonth(MdMedDimVO dimVO)
    {
        dimVO.setMonth(dimVO.getMonth().replaceAll("-",""));
        List<Map<String,Object>> data = mdMedDimService.queryDayData(dimVO.getMonth());
        return getDataTable(data);
    }

    @GetMapping("/addFld/{tableName}")
    public String addFld(@PathVariable("tableName") String tableName, ModelMap mmap)
    {
        mmap.put("tableName", tableName);
        return prefix + "/add";
    }

    @GetMapping("/addData/{tableName}")
    public String addData(@PathVariable("tableName") String tableName, ModelMap mmap)
    {
        mmap.put("tableName", tableName);
        return prefix + "/addData";
    }

    @PostMapping("/saveDimData")
    @ResponseBody
    public AjaxResult saveDimData(@RequestBody DimDataVO dataVO)
    {
        Map<String,List<DimDataVO>> map = new HashMap<>();
        List<DimDataVO> list = new ArrayList<>();
        list.add(dataVO);
        map.put(dataVO.getTableName(),list);
        mdMedDimService.insertDimDatas(map);
        return AjaxResult.success();
    }

    @PostMapping("/saveDimFld")
    @ResponseBody
    public AjaxResult saveDimFld(@RequestBody MdMedTbFldVO fldVO)
    {
        MdMedTb mdMedTb = new MdMedTb();
        mdMedTb.setCd(fldVO.getTableName());
        MdMedTbFld fld = new MdMedTbFld();
        fld.setCdTb(fldVO.getTableName());
        List<MdMedTbFld> fldList = mdMedTbFldService.selectMdMedTbFldList(fld);
        Boolean isSuccess = false;
        if(fldList!=null) {
            fldList.add(fldVO.getMdMedTbFld());
            return commonTableDDLService.alterTableByMedOtherDB(new AlterTableParamVO(mdMedTb, fldList, null), JobConstant.DB_CLS_DW);
        }
        return AjaxResult.success("执行成功");
    }

    @Log(title = "系统字典", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(MdMedTbFld tbFld)
    {
        return toAjax(mdMedTbFldService.updateMdMedTbFld(tbFld));
    }

    @ApiOperation(value = "查询维度数据")
    @GetMapping(value = "/findDimData/{cdTb}")
    @ResponseBody
    public AjaxResult findDimData(@PathVariable("cdTb") String tableName) throws BaseException {
        MdMedTbFld fld = new MdMedTbFld();
        fld.setCdTb(tableName);
        List<MdMedTbFld> tbFldList = mdMedTbFldService.selectMdMedTbFldList(fld);
        List<Map<String,Object>> data = mdMedDimService.findDimDataByTbname(tbFldList,tableName);
        Map<String,Object> returnMap = new HashMap<>();
        returnMap.put("data",data);
        returnMap.put("fldList",tbFldList);
        return AjaxResult.success(returnMap);
    }

    @ApiOperation(value = "查询维度数据")
    @GetMapping(value = "/findDimDataByPage")
    @ResponseBody
    public TableDataInfo findDimDataByPage(String tableName,String search) throws BaseException {
        MdMedTbFld fld = new MdMedTbFld();
        fld.setCdTb(tableName);
        List<MdMedTbFld> tbFldList = mdMedTbFldService.selectMdMedTbFldList(fld);
        List<Map<String,Object>> data = mdMedDimService.findDimDataByTbname(tbFldList,tableName,search);
        return getDataTable(data);
    }

    @ApiOperation(value = "查询维度数据")
    @GetMapping(value = "/findDimData2/{cdTb}")
    @ResponseBody
    public TableDataInfo findDimData2(@PathVariable("cdTb") String tableName) throws BaseException {
        MdMedTbFld fld = new MdMedTbFld();
        fld.setCdTb(tableName);
        List<MdMedTbFld> tbFldList = mdMedTbFldService.selectMdMedTbFldList(fld);
        List<Map<String,Object>> data = mdMedDimService.findDimDataByTbname(tbFldList,tableName);
        Map<String,Object> all = new HashMap<>();
        all.put("cd","000");all.put("na","全部");
        List<Map<String,Object>> dataList = new ArrayList<>();
        dataList.add(all);dataList.addAll(data);
        return getDataTable(dataList);
    }

    @ApiOperation(value = "删除维度数据")
    @GetMapping(value = "/remove")
    @ResponseBody
    public AjaxResult remove(String tableName,String cd) throws BaseException {
        int i = mdMedDimService.remove(tableName,cd);
        return AjaxResult.success();
    }

    @ApiOperation(value="插入天数据")
    @RequestMapping(value="insertDay", method= RequestMethod.GET)
    @ResponseBody
    public void insertDay(String startDate,String endDate) {
        MdMedTbFld fldModel = new MdMedTbFld();
        fldModel.setCdTb("MD_DIM_DAY");
        List<MdMedTbFld> fldList = mdMedTbFldService.selectMdMedTbFldList(fldModel);
        if(fldList.size()==0) return;
        boolean isCre=false;
        for(MdMedTbFld fld:fldList) {
            if("MM".equals(fld.getIdPubfld().toUpperCase())) {
                isCre=true;
                break;
            }
        }
        if(!isCre) {
            List<MdMedTbFld> mdMedTbFlds = generateOther();
            mdMedTbFlds.addAll(fldList);
            MdMedTb mdMedTb = mdMedTbService.selectMdMedTbByCd("MD_DIM_DAY");
            commonTableDDLService.alterTableByMedOtherDB(new AlterTableParamVO(mdMedTb, mdMedTbFlds, null), JobConstant.DB_CLS_DW);
        }
        List<Map<String,Object>> list = new ArrayList<>();
        try {
            Date dtBegin = DateUtil.FORMAT_YYYY_MM_DD_HHMMSS.parse(startDate+" 00:00:00");
            Date dtEnd = DateUtil.FORMAT_YYYY_MM_DD_HHMMSS.parse(endDate+" 00:00:00"),dtNext;
            String dBegin;int counterStop=0;
            Map<String,Object> dayMap = new TreeMap<>();
            while (dtBegin.before(dtEnd) && counterStop++ < 10000) {
                if(counterStop%200==0 && list.size()>0) {
                    baseDWService.insertMapList("md_dim_day",list.get(0),list);
                    list = new ArrayList<>();
                }
                dBegin = DateUtil.toDateStrByFormat(dtBegin, "yyyyMMdd");
                dayMap = new TreeMap<>();
                dayMap.put("cd",dBegin);dayMap.put("mm",dBegin.substring(0,6));dayMap.put("yy",dBegin.substring(0,4));
                dayMap.put("qq",dBegin.substring(0,4)+(Integer.parseInt(dBegin.substring(4,6))+2)/3);
                dayMap.put("ww",DateUtil.getWeek(dtBegin)+"");
                dayMap.put("eu_class", DateUtils.judgeHoliday(dBegin));
                list.add(dayMap);
                dtNext = DateUtil.getNextDate(dtBegin, 3);
                dtBegin = dtNext;
            }
            if(list.size()>0) {
                baseDWService.insertMapList("md_dim_day",list.get(0),list);
            }
        }catch (Exception e) {
            e.printStackTrace();
        }
    }

    private List<MdMedTbFld> generateOther() {
        List<MdMedTbFld> mdMedTbFlds = new ArrayList();
        MdMedTbFld one = new MdMedTbFld();
        one.setIdPubfld("mm");
        one.setNaPubfld("月");
        one.setNumLth(6);
        one.setNumPrec(0);
        one.setEuJavatp(12);
        one.setNaJavatp("VARCHAR");
        mdMedTbFlds.add(one);
        one = new MdMedTbFld();
        one.setIdPubfld("qq");
        one.setNaPubfld("季度");
        one.setNumLth(5);
        one.setNumPrec(0);
        one.setEuJavatp(12);
        one.setNaJavatp("VARCHAR");
        mdMedTbFlds.add(one);
        one = new MdMedTbFld();
        one.setIdPubfld("yy");
        one.setNaPubfld("年");
        one.setNumLth(4);
        one.setNumPrec(0);
        one.setEuJavatp(12);
        one.setNaJavatp("VARCHAR");
        mdMedTbFlds.add(one);
        one = new MdMedTbFld();
        one.setIdPubfld("ww");
        one.setNaPubfld("周");
        one.setNumLth(1);
        one.setNumPrec(0);
        one.setEuJavatp(12);
        one.setNaJavatp("VARCHAR");
        mdMedTbFlds.add(one);
        one = new MdMedTbFld();
        one.setIdPubfld("eu_class");
        one.setNaPubfld("分类");
        one.setNumLth(1);
        one.setNumPrec(0);
        one.setEuJavatp(12);
        one.setNaJavatp("VARCHAR");
        mdMedTbFlds.add(one);
        return mdMedTbFlds;
    }
}
